package pri.hillchen.std.concurrent.chapter14.boundedbuffer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 14:49 2018/2/13 0013.
 */
public class ThreadGate {
    private final int generation;

    public ThreadGate(int generation) {
        this.generation = generation;
    }

    private AtomicInteger waitCount = new AtomicInteger(0);
    public synchronized void close(){
        this.waitCount.set(0);
    }

    public synchronized void countDown() throws InterruptedException {
        int wc = waitCount.addAndGet(1);
        while (wc < generation){
            wait();
        }
        notifyAll();
    }
    public synchronized void await() throws InterruptedException {
        wait();
    }

    public static void main(String[] args) throws InterruptedException {
        final ThreadGate end = new ThreadGate(1);
        final ThreadGate star = new ThreadGate(1);
        for(int i = 0;i<1;i++){
            final int threadId = i+1;
            new Thread(){
                @Override
                public void run() {
                    try {
                        star.await();
                        System.out.println(threadId);
                        TimeUnit.MICROSECONDS.sleep(5000);
                        end.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        TimeUnit.MICROSECONDS.sleep(1000);
        star.countDown();
        end.await();

        System.out.println("!!!!!!!!!!!end");
    }
}
